//
// definition of main scene
//
var NUMBER_OF_KAWAZ = 9;
var gameBGMIntro = null;
var gameBGM      = null;
var bombSE       = null;
var fireSE       = null;

var MainScene = {
    scene:null,
    background:null,
    forelayer0:null,
    forelayer1:null,
    finishText:null,
    goText:null,
    readyText:null,
    loaded:false,
    started:false,
    kawaz:Array(NUMBER_OF_KAWAZ),
    leftCurtain:null,
    rightCurtain:null,
    readyTextTransform:null,
    goTextTransform:null,
    kawazTransforms:Array(NUMBER_OF_KAWAZ),
    init:function() {
        this.scene = quicktigame2d.createScene();
            	        
        var onReadyTextCompleted = (function(self) {
            return function(e) {
            	if (self.readyTextTransform.completed) {
            		self.readyText.hide();
            		
					self.scene.add(self.goText);
            		
					self.goTextTransform.delay    = 0;
					self.goTextTransform.duration = 500;
					
					self.goText.transform(self.goTextTransform);
            	} else {
					self.readyTextTransform.duration = 0;
					self.readyTextTransform.delay = 1000;
					self.readyTextTransform.completed = true;
					self.readyText.transform(self.readyTextTransform);
				}
            };
        })(this);
            
        var onGoTextCompleted = (function(self) {
            return function(e) {
            	if (self.goTextTransform.completed) {
					self.scene.remove(self.goText);
            	} else {
            		self.goTextTransform.rotate(360);
            		self.goTextTransform.x = game.screen.width;
            		self.goTextTransform.y = -self.goText.height * 0.5;
            		self.goTextTransform.completed = true;
					self.goText.transform(self.goTextTransform);
            	}
            };
        })(this);
        

        var onKawazCompleted = (function(self) {
            return function(e) {
            	var transform = e.source;
            	var kawaztan = self.kawaz[transform.index];
            	if (kawaztan.status == "moving") {
            		// just wait for 1 second
	        		kawaztan.status = "appear";
            		transform.duration = 1000;
                	kawaztan.transform(transform);
            	} else if (kawaztan.status == "appear") {
            		kawaztan.status = "hiding";
            		transform.duration = 500;
					transform.x = kawaztan.x;
					transform.y = kawaztan.waitingY;
                	transform.easing = quicktigame2d.ANIMATION_CURVE_CUBIC_OUT;
                	kawaztan.transform(transform);
              	} else if (kawaztan.status == "hiding") {
            		// just wait for 1 second
              		kawaztan.status = "queue_waiting";
            		transform.duration = 1000;
                	kawaztan.transform(transform);
               } else if (kawaztan.status == "queue_waiting") {
               		kawaztan.status = "waiting";
		        	kawaztan.selectFrame("kawaz0");
              	} else if (kawaztan.status == "damaging") {
            		kawaztan.status = "hiding";
            		transform.duration = 500;
					transform.x = kawaztan.x;
					transform.y = kawaztan.waitingY;
                	transform.easing = quicktigame2d.ANIMATION_CURVE_CUBIC_OUT;
                	kawaztan.transform(transform);
              	}
            };
        })(this);
        
        var onloadsprite = (function(self) {
            return function(e) {
                Ti.API.info("onloadsprite: " + e.name);
                if (e.name == "graphics/main/main_layer1.png") {
                    game.startCurrentScene();
                    self.loaded = true;

					// show ready text
					self.readyTextTransform.delay    = 0;
					self.readyTextTransform.duration = 1000;
					self.readyTextTransform.easing   = quicktigame2d.ANIMATION_CURVE_BACK_OUT;
					self.readyTextTransform.scale(1, 1);
					
					self.readyText.transform(self.readyTextTransform);
                    
	                gameBGMIntro.play();
                }
            };
        })(this);
        
        var enterframe = (function(self) {
            return function(e) {
                if (!self.loaded) return;
                if (!self.started) return;
                for (var i = 0; i < NUMBER_OF_KAWAZ; i++) {
                	if (self.kawaz[i].status == "waiting") {
                		var kawazX = self.kawaz[i].x;
                		var kawazY = self.kawaz[i].y;
                		var randomNumber = Math.random();
                		if (randomNumber > 0.9) {
                			// check if neighboring kawaz is active
                			if (i == 0 && self.kawaz[1].status != "waiting") continue;
                			if (i > 0  && self.kawaz[i - 1].status != "waiting") continue;
                			if (i < NUMBER_OF_KAWAZ - 1 && self.kawaz[i + 1].status != "waiting") continue;

                			self.kawazTransforms[i].duration = 500;
                			self.kawazTransforms[i].delay    = 0;
                			self.kawazTransforms[i].x = kawazX;
                			self.kawazTransforms[i].y = self.kawaz[i].waitingY - self.kawaz[i].height;
                			self.kawazTransforms[i].easing = quicktigame2d.ANIMATION_CURVE_CUBIC_IN;
                			self.kawaz[i].transform(self.kawazTransforms[i]);
							
							var face = Math.floor((randomNumber * 100) % 3);
							switch(face) {
								case 0: self.kawaz[i].selectFrame("kawaz0"); break;
								case 1: self.kawaz[i].selectFrame("kawaz1"); break;
								case 2: self.kawaz[i].selectFrame("kawaz2"); break;
							}
                			self.kawaz[i].status = "moving";
                			break;
                		}
                	}
                }
            };
        })(this);
        
        var touchstart = (function(self) {
            return function(e) {
                // fix coordinates because view touch event returns non-retina values.
                var x = e.x * WINDOW_SCALE_FACTOR_X;
                var y = e.y * WINDOW_SCALE_FACTOR_Y;

                if (!self.loaded) return;
                if (!self.started) return;
                for (var i = 0; i < NUMBER_OF_KAWAZ; i++) {
                	if (self.kawaz[i].status == "appear" || self.kawaz[i].status == "moving") {
                		if (self.kawaz[i].contains(x, y)) {
 		                	picoSE.play();
                			self.kawaz[i].selectFrame("damage");
                			self.kawaz[i].status = "damaging";
                			
                			// Clear all transforms from the sprite
                			self.kawaz[i].clearTransforms();
                			
                			// Keep damage sprite for 1 second
		            		self.kawazTransforms[i].duration = 1000;
        		        	self.kawaz[i].transform(self.kawazTransforms[i]);
							
                			break;
                		}
                	}
                }
                
            };
        })(this);
        
        var touchend = (function(self) {
            return function(e) {
                // fix coordinates because view touch event returns non-retina values.
                var x = e.x * WINDOW_SCALE_FACTOR_X;
                var y = e.y * WINDOW_SCALE_FACTOR_Y;
                
            };
        })(this);
        
        var activated = (function(self) {
            return function(e) {
                Ti.API.info("main scene is activated");
            
                self.loaded  = false;
                self.started = false;
                
                // Set background color to black
                self.scene.color(0, 0, 0);
                
                // Create sprite instance    
                if (self.background == null) {
                    self.background = quicktigame2d.createSprite({image:'graphics/main/main_background.png'});
                }
                if (self.forelayer0 == null) {
                    self.forelayer0 = quicktigame2d.createSprite({image:'graphics/main/main_layer0.png'});
                }
                if (self.forelayer1 == null) {
                    self.forelayer1 = quicktigame2d.createSprite({image:'graphics/main/main_layer1.png'});
                }
                if (self.finishText == null) {
                	self.finishText = quicktigame2d.createSprite({image:'graphics/main/text/finish.png'});
                }
                if (self.goText == null) {
                	self.goText     = quicktigame2d.createSprite({image:'graphics/main/text/go.png'});
                }
                if (self.readyText == null) {
                	self.readyText  = quicktigame2d.createSprite({image:'graphics/main/text/ready.png'});
                }
                
                if (self.readyTextTransform == null) {
                	self.readyTextTransform = quicktigame2d.createTransform();
                	self.readyTextTransform.addEventListener('complete', onReadyTextCompleted)
                }
                if (self.goTextTransform == null) {
                	self.goTextTransform = quicktigame2d.createTransform();
                	self.goTextTransform.addEventListener('complete', onGoTextCompleted)
                }
                
                if (self.background.width < game.screen.width) {
                	var curtainWidth = Math.ceil((game.screen.width - self.background.width) * 0.5);
	                // hide left margin
	                if (self.leftCurtain == null) {
    	            	self.leftCurtain = quicktigame2d.createSprite({width:curtainWidth,height:game.screen.height});
        	        }
	                // hide right margin
	                if (self.rightCurtain == null) {
    	            	self.rightCurtain = quicktigame2d.createSprite({width:curtainWidth,height:game.screen.height});
        	        }
                }
                
    			// set background at center of the screen
                self.background.x = (game.screen.width   * 0.5) - (self.background.width   * 0.5);
                self.background.y = (game.screen.height  * 0.5) - (self.background.height  * 0.5);
                self.forelayer0.x = (game.screen.width   * 0.5) - (self.background.width   * 0.5);
                self.forelayer0.y = (game.screen.height  * 0.5) - (self.background.height  * 0.5);
                self.forelayer1.x = (game.screen.width   * 0.5) - (self.background.width   * 0.5);
                self.forelayer1.y = (game.screen.height  * 0.5) - (self.background.height  * 0.5);

				if (self.leftCurtain != null && self.rightCurtain != null) {
					self.leftCurtain.color(0, 0, 0);
					self.rightCurtain.color(0, 0, 0);
					
                	self.leftCurtain.x  = 0;
                	self.rightCurtain.x = game.screen.width - self.rightCurtain.width;
                	
                	self.leftCurtain.y  = 0;
                	self.rightCurtain.y = 0;
                	
                	self.leftCurtain.z  = 11;
                	self.rightCurtain.z = 11;
                	
                	self.scene.add(self.leftCurtain);
                	self.scene.add(self.rightCurtain);
               	}
                
                self.background.z = 0;
                self.forelayer0.z = 2;
                self.forelayer1.z = 4;
                self.finishText.z = 10;
                self.goText.z     = 10;
                self.readyText.z  = 10;
                
                self.readyText.scale(0, 0);
	                
                self.scene.add(self.background);
                self.scene.add(self.forelayer0);
                self.scene.add(self.forelayer1);
	            self.scene.add(self.readyText);
                
                for (var i = 0; i < NUMBER_OF_KAWAZ; i++) {
                	self.kawaz[i] = quicktigame2d.createSpriteSheet({image:'graphics/main/kawaztan.xml'});
                	if (i < 6) {
                		self.kawaz[i].x = (i * self.kawaz[i].width * 0.5);
                		self.kawaz[i].y = game.screen.height - (self.kawaz[i].height * 0.5);
                		self.kawaz[i].z = 3;
                	} else {
                		self.kawaz[i].x = (game.screen.width - self.kawaz[i].width) - ((i - 6) * self.kawaz[i].width * 0.5);
                		self.kawaz[i].y = game.screen.height - (self.kawaz[i].height * 0.7);
                		self.kawaz[i].z = 1;
                	}

					self.kawaz[i].index = i;
                	self.kawaz[i].waitingY = self.kawaz[i].y;
                	self.kawaz[i].status = "waiting";
                	self.kawaz[i].selectFrame("kawaz0");
                	self.scene.add(self.kawaz[i]);
                	
                	if (self.kawazTransforms[i] == null) {
                		self.kawazTransforms[i] = quicktigame2d.createTransform();
                		self.kawazTransforms[i].addEventListener('complete', onKawazCompleted);
                		self.kawazTransforms[i].index = i;
                	}
                }
                
                self.finishText.x = (game.screen.width * 0.5) - (self.finishText.width * 0.5);
                self.goText.x     = (game.screen.width * 0.5) - (self.goText.width * 0.5);
                self.readyText.x  = (game.screen.width * 0.5) - (self.readyText.width * 0.5);
                
                self.finishText.y = (game.screen.height * 0.5) - (self.finishText.height * 0.5);
                self.goText.y     = (game.screen.height * 0.5) - (self.goText.height * 0.5);
                self.readyText.y  = (game.screen.height * 0.5) - (self.readyText.height * 0.5);
                
                gameBGMIntro = Ti.Media.createSound({url:'/music/bgm_int.wav'});
                gameBGM      = Ti.Media.createSound({url:'/music/bgm.wav'});
                bombSE       = Ti.Media.createSound({url:'/se/bomb.wav'});
                fireSE       = Ti.Media.createSound({url:'/se/fire.wav'});
                
                gameBGMIntro.addEventListener('complete', function(e) {
                	gameBGMIntro.stop();
                	gameBGM.play();
                	gameBGM.setLooping(true);
                	self.started = true;
                });
                
                // Start handling touch event
                game.addEventListener('touchstart', touchstart);
                game.addEventListener('touchend', touchend);
            };
        })(this);
        
        var deactivated = (function(self) {
            return function(e) {
                Ti.API.info("main scene is deactivated");
            
                // remove logo from the scene and set variable null
                // that triggers removal from the memory at GC.
                self.scene.remove(self.background);
                self.background = null;
                
                self.scene.remove(self.forelayer0);
                self.scene.remove(self.forelayer1);
                self.forelayer0 = null;
                self.forelayer1 = null;
                
                if (self.leftCurtain != null ) {
                	self.scene.remove(self.leftCurtain);
                	self.leftCurtain = null;
                }
                if (self.rightCurtain != null ) {
                	self.scene.remove(self.rightCurtain);
                	self.rightCurtain = null;
                }
                
                for (var i = 0; i < NUMBER_OF_KAWAZ; i++) {
                	self.scene.remove(self.kawaz[i]);
                	self.kawaz[i] = null;
                }
                
               	self.kawaz.length = 0;
                	
            	if (gameBGM != null) {
            		gameBGM.stop();
            		gameBGM = null;
            	}
            	if (gameBGMIntro != null) {
            		gameBGMIntro.stop();
            		gameBGMIntro = null;
            	}
            	
            	self.readyTextTransform = null;
            	self.goTextTransform    = null;
            	
                self.loaded  = false;
                self.started = false;
                
                // Stop handling touch event
                game.removeEventListener('touchstart', touchstart);
                game.removeEventListener('touchend',   touchend);
            };
        })(this);
        
        // register scene activationi event
        this.scene.addEventListener('activated',   activated);
        this.scene.addEventListener('deactivated', deactivated);
        this.scene.addEventListener('onloadsprite',  onloadsprite);
        this.scene.addEventListener('enterframe',  enterframe);
    },
};
